package org.gg.boom.modules.sys.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.gg.boom.common.controller.BaseController;
import org.gg.boom.common.model.BaseParam;
import org.gg.boom.common.model.Response;
import org.gg.boom.common.utils.SecurityUtils;
import org.gg.boom.common.utils.StringUtils;
import org.gg.boom.common.utils.poi.ExcelUtil;
import org.gg.boom.kernel.annotation.Log;
import org.gg.boom.kernel.enums.BusinessType;
import org.gg.boom.modules.sys.constant.UserConstants;
import org.gg.boom.modules.sys.model.entity.SysRole;
import org.gg.boom.modules.sys.model.entity.SysUser;
import org.gg.boom.modules.sys.model.param.SysDeptParam;
import org.gg.boom.modules.sys.model.param.SysUserParam;
import org.gg.boom.modules.sys.model.vo.SysRoleResult;
import org.gg.boom.modules.sys.model.vo.SysUserResult;
import org.gg.boom.modules.sys.service.SysDeptService;
import org.gg.boom.modules.sys.service.SysPostService;
import org.gg.boom.modules.sys.service.SysRoleService;
import org.gg.boom.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysPostService postService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public Response list(SysUserParam param) {
        Page<SysUserResult> page = userService.selectUserList(param);
        return getDataTable(page);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserParam param) {
        Page<SysUserResult> page = userService.selectUserList(param);
        ExcelUtil<SysUserResult> util = new ExcelUtil<>(SysUserResult.class);
        util.exportExcel(response, page.getRecords(), "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public Response importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public Response getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        JSONObject result = new JSONObject();
        List<SysRoleResult> roles = roleService.selectRoleAll();
        result.put("roles", UserConstants.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        result.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUserResult sysUser = userService.selectUserById(userId);
            result.put("user", sysUser);
            result.put("postIds", postService.selectPostListByUserId(userId));
            result.put("roleIds", sysUser.getRoles().stream().map(SysRoleResult::getRoleId).collect(Collectors.toList()));
        }
        return success(result);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Response add(@Validated(BaseParam.add.class) @RequestBody SysUserParam param) {
        param.setPassword(SecurityUtils.encryptPassword(param.getPassword()));
        return toResponse(userService.insertUser(param));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response edit(@Validated @RequestBody SysUserParam param) {
        userService.checkUserAllowed(param.getUserId());
        userService.checkUserDataScope(param.getUserId());
        return toResponse(userService.updateUser(param));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public Response remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toResponse(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public Response resetPwd(@RequestBody SysUserParam param) {
        userService.checkUserAllowed(param.getUserId());
        userService.checkUserDataScope(param.getUserId());
        param.setPassword(SecurityUtils.encryptPassword(param.getPassword()));
        return toResponse(userService.resetPwd(param));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public Response changeStatus(@RequestBody SysUserParam param) {
        userService.checkUserAllowed(param.getUserId());
        userService.checkUserDataScope(param.getUserId());
        return toResponse(userService.updateUserStatus(param));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public Response authRole(@PathVariable("userId") Long userId) {
        JSONObject result = new JSONObject();
        SysUserResult user = userService.selectUserById(userId);
        List<SysRoleResult> roles = roleService.selectRolesByUserId(userId);
        result.put("user", user);
        result.put("roles", UserConstants.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return success(result);
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public Response insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public Response deptTree(SysDeptParam param) {
        return success(deptService.selectDeptTreeList(param));
    }
}
